package com.ravi.websocket.endpoint;

import com.ravi.websocket.config.SessionPool;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@ServerEndpoint("/websocket/{queueid}")
@Component
public class WaitingQueueEndPoint {

	private Session session;

	@OnOpen
	public void onOpen(Session session, @PathParam("queueid") String queueid) {
		this.session = session;
		SessionPool.sessions.put(queueid, session);
	}

	@OnClose
	public void onClose(Session session) {
		try {
			SessionPool.close(session.getId());
			session.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@OnMessage
	public void onMessage(Session session, String message) {
		System.out.println("来自客户端的消息:" + message);
		SessionPool.sendMessage(message);
	}
}
